package com.jinzhi.jzweb.controller.api;

import com.aliyun.ocr_api20210707.models.RecognizeAllTextResponseBody;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jinzhi.common.utils.IdCardUtils;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzapi.utils.SampleUtil;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.oss.service.OssService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author mengzhichao
 * @create 2024-09-06-11:30
 * 报名模块
 */
@RestController
@RequestMapping("/jzApi/ApiJazSignup")
public class JazSignupController {

    @Autowired
    private JazSignupTeamService jazSignupTeamService;  //报名队伍表

    @Autowired
    private JazSignupUserService jazSignupUserService;  //报名选手表

    @Autowired
    private JazSignupGroupService jazSignupGroupService;  //报名组别表

    @Autowired
    private JazSignupItemService jazSignupItemService;  //参赛项目表

    @Autowired
    private JazSignupResultService jazSignupResultService;  //参赛成绩表

    @Autowired
    private OssService ossService;


    //手机号校验正则
    private static final Pattern PHONE_NUMBER_PATTERN = Pattern.compile("^1(([3][0-9])|([4][014-9])|([5][0-35-9])|([6][2567])|([7][0-8])|([8][0-9])|([9][0-35-9]))[0-9]{8}$");


    public  boolean validatePhoneNumber(String orderPhone) {
        Matcher matcher = PHONE_NUMBER_PATTERN.matcher(orderPhone);
        return matcher.matches();
    }


    /**
     * 查询队伍信息
     * @return
     */
    @GetMapping("/selTeam")
    public Result<?> selTeam(String name){
        EntityWrapper<JazSignupTeamDO> entityWrapper =new EntityWrapper();
        if (name!=null&&!name.equals("")) {
            entityWrapper.eq("name", name);
        }
        List<JazSignupTeamDO> list = jazSignupTeamService.selectList(entityWrapper);
        return Result.ok(list);
    }



    /**
     * 查询组别信息
     * @return
     */
    @GetMapping("/selGroup")
    public Result<?> selGroup(String name){
        EntityWrapper<JazSignupGroupDO> entityWrapper =new EntityWrapper();
        if (name!=null&&!name.equals("")) {
            entityWrapper.eq("name", name);
        }
        List<JazSignupGroupDO> list = jazSignupGroupService.selectList(entityWrapper);
        return Result.ok(list);
    }


    /**
     * 根据身份证图片解析身份证号码
     * @param file
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/uploadByGetNumber")
    public Result<String> upload(@RequestParam("file") MultipartFile file) throws Exception {
        String url = "";
        //url = fileService.upload(file.getBytes(), file.getOriginalFilename());
        url = ossService.uploadFileOss(file);
        String idNumber= SampleUtil.identifyImages1(url);

        return Result.ok(idNumber);
    }


    /**
     * 查询参赛项目下拉框
     * @return
     */
    @GetMapping("/selItem")
    public Result<?> selItem(String name,String groupId){
        EntityWrapper<JazSignupItemDO> entityWrapper =new EntityWrapper();
        if (name!=null&&!name.equals("")) {
            entityWrapper.eq("name", name);
        }
        if (groupId!=null&&!groupId.equals("")) {
            entityWrapper.eq("group_id", groupId);
        }
        List<JazSignupItemDO> list = jazSignupItemService.selectList(entityWrapper);
        return Result.ok(list);
    }

    /**
     * 新增领队信息
     * @return
     */
    @PostMapping("/addSignupLeaderUser")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> addSignupLeaderUser(JazSignupUserDO jazSignupUserDO){
        if (jazSignupUserDO==null){
            return Result.fail();
        }

        String identityCard = jazSignupUserDO.getIdentityCard(); //获取身份证号码

        String phone = jazSignupUserDO.getPhone();//获取手机号

        EntityWrapper<JazSignupUserDO> entityWrapper =new EntityWrapper();
        entityWrapper.eq("identity_card", identityCard);
        List<JazSignupUserDO> isIdentityCard = jazSignupUserService.selectList(entityWrapper);
        if (isIdentityCard.size()>0){
            return Result.fail("该身份证已报过名，请勿重复报名！");
        }

        entityWrapper =new EntityWrapper<>();
        entityWrapper.eq("phone", phone);
        List<JazSignupUserDO> isPhone = jazSignupUserService.selectList(entityWrapper);
        if (isPhone.size()>0){
            return Result.fail("该手机号已报过名，请勿重复报名！");
        }

        //校验手机号
        if(StringUtil.notEmpty(jazSignupUserDO.getPhone())){
            if (!validatePhoneNumber(jazSignupUserDO.getPhone())) {
                return Result.fail("电话号码格式错误");
            }
        }

        UserDO getUser = JWTUtil.getUser();
        jazSignupUserDO.setUserId(getUser.getId()); //创建人
        jazSignupUserDO.setCreateTime(new Date()); //创建时间
        jazSignupUserDO.setUpdateTime(new Date()); //修改时间
        jazSignupUserDO.setStatus(1);//默认待审核
        jazSignupUserDO.setType(1); // 领队

        // 查询队伍是否进行过新增
        JazSignupTeamDO teamDO = jazSignupTeamService.selectOne(new EntityWrapper<JazSignupTeamDO>().eq("name", jazSignupUserDO.getTeamName()));
        JazSignupTeamDO jazSignupTeamDO;
        if (teamDO==null){
            // 新增队伍
            jazSignupTeamDO = new JazSignupTeamDO();
            // 队伍名称
            jazSignupTeamDO.setName(jazSignupUserDO.getTeamName());
            // 队伍创建人
            jazSignupTeamDO.setCreateUserId(getUser.getId());
            jazSignupTeamDO.setCreateTime(new Date());
            jazSignupTeamDO.setUpdateTime(new Date());
            jazSignupTeamDO.setGroupId(jazSignupUserDO.getGroupId());
            boolean insert = jazSignupTeamService.insert(jazSignupTeamDO);
            if (!insert){
                return Result.fail("新增队伍失败！");
            }

            // 设置队伍id
            jazSignupUserDO.setTeamId(jazSignupTeamDO.getId());
        }else {
            // 判断是否存在领队信息
            List<JazSignupUserDO> list = jazSignupUserService.selectList(new EntityWrapper<JazSignupUserDO>()
                    .eq("team_id", teamDO.getId())
                    .eq("group_id", teamDO.getGroupId()).eq("type",1));
            if (list.size()>0){
                return Result.fail("该队伍已存在领队，请勿重复添加");
            }
            jazSignupUserDO.setTeamId(teamDO.getId());

            //return Result.fail("队伍已存在请勿重复添加");
        }
        jazSignupUserService.insert(jazSignupUserDO);
        return Result.ok();
    }



    /**
     * 新增选手信息
     * @return
     */
    @PostMapping("/addSignupUser")
    public Result<?> addSignupUser(JazSignupUserDO jazSignupUserDO){

        String identityCard = jazSignupUserDO.getIdentityCard(); //获取身份证号码

        String phone = jazSignupUserDO.getPhone();//获取手机号

        EntityWrapper<JazSignupUserDO> entityWrapper =new EntityWrapper();
        entityWrapper.eq("identity_card", identityCard);
        List<JazSignupUserDO> isIdentityCard = jazSignupUserService.selectList(entityWrapper);
        if (isIdentityCard.size()>0){
            return Result.fail("该身份证已报过名，请勿重复报名！");
        }

        entityWrapper =new EntityWrapper<>();
        entityWrapper.eq("phone", phone);
        List<JazSignupUserDO> isPhone = jazSignupUserService.selectList(entityWrapper);
        if (isPhone.size()>0){
            return Result.fail("该手机号已报过名，请勿重复报名！");
        }

        // 校验身份证号
        if(StringUtil.notEmpty(jazSignupUserDO.getIdentityCard())){
            if (!IdCardUtils.isIdcard(jazSignupUserDO.getIdentityCard())) {
                return Result.fail("身份证号码不正确，请输入正确的身份证号");
            }
        }

        //校验手机号
        if(StringUtil.notEmpty(jazSignupUserDO.getPhone())){
            if (!validatePhoneNumber(jazSignupUserDO.getPhone())) {
                return Result.fail("电话号码格式错误");
            }
        }

        UserDO getUser = JWTUtil.getUser();
        jazSignupUserDO.setUserId(getUser.getId()); //创建人
        jazSignupUserDO.setCreateTime(new Date()); //创建时间
        jazSignupUserDO.setUpdateTime(new Date()); //修改时间
        jazSignupUserDO.setStatus(1);//默认待审核
        jazSignupUserDO.setType(2); // 选手

        // 设置队伍名称
        JazSignupTeamDO jazSignupTeamDO = jazSignupTeamService.selectById(jazSignupUserDO.getTeamId());
        if (jazSignupTeamDO!=null){
            jazSignupUserDO.setTeamName(jazSignupTeamDO.getName());
        }

        jazSignupUserService.insert(jazSignupUserDO);
        return Result.ok();
    }


    /**
     * 成绩公示
     * @return
     */
    @GetMapping("/selResult")
    public Result<?> selResult(Long groupId,Long itemId){
        EntityWrapper<JazSignupResultDO> entityWrapper =new EntityWrapper();
        if (groupId!=null&&!groupId.equals("")) {
            entityWrapper.eq("group_id", groupId);
        }
        if (itemId!=null&&!itemId.equals("")) {
            entityWrapper.eq("item_id", itemId);
        }
        List<JazSignupResultDO> jazSignupResultDOS = jazSignupResultService.selectList(entityWrapper);
        for (int i=0;i<jazSignupResultDOS.size();i++){
            JazSignupResultDO jazSignupResultDO = jazSignupResultDOS.get(i);
            JazSignupGroupDO jazSignupGroupDO = jazSignupGroupService.selectById(jazSignupResultDO.getGroupId());
            jazSignupResultDO.setGroupName(jazSignupGroupDO.getName()); //组别名称

            JazSignupItemDO jazSignupItemDO = jazSignupItemService.selectById(jazSignupResultDO.getItemId());
            jazSignupResultDO.setItemName(jazSignupItemDO.getName()); //参赛项目名称
        }
        return Result.ok(jazSignupResultDOS);
    }





    /**
     * 修改选手信息
     * @return
     */
    @PostMapping("/updateSignupUser")
    @Transactional
    public Result<?> updateSignupUser(JazSignupUserDO jazSignupUserDO){
        JazSignupUserDO userDO = jazSignupUserService.selectById(jazSignupUserDO.getId());
        if (userDO==null){
            return Result.fail();
        }
        jazSignupUserDO.setUpdateTime(new Date()); //修改时间
        jazSignupUserDO.setStatus(1);//默认待审核
        jazSignupUserDO.setResult(0);//审核结果
        jazSignupUserDO.setRefuseReasion(null);//拒绝原因 设置为null
        jazSignupUserDO.setReviewTime(null);//审核时间 设置为null
        // 查询队伍
        JazSignupTeamDO jazSignupTeamDO = jazSignupTeamService.selectById(jazSignupUserDO.getTeamId());
        if (jazSignupTeamDO!=null){
            jazSignupUserDO.setTeamId(jazSignupTeamDO.getId());
        }
        if (userDO.getType()==1){
            // 修改队伍名称
            jazSignupTeamDO.setName(jazSignupUserDO.getTeamName());
            jazSignupTeamService.updateById(jazSignupTeamDO);
        }else if (userDO.getType()==2){
            // 修改队伍名称
            jazSignupUserDO.setTeamName(jazSignupTeamDO.getName());
        }

        // 校验身份证号
        if(StringUtil.notEmpty(jazSignupUserDO.getIdentityCard())){
            if (!IdCardUtils.isIdcard(jazSignupUserDO.getIdentityCard())) {
                return Result.fail("身份证号码不正确，请输入正确的身份证号");
            }
        }

        //校验手机号
        if(StringUtil.notEmpty(jazSignupUserDO.getPhone())){
            if (!validatePhoneNumber(jazSignupUserDO.getPhone())) {
                return Result.fail("电话号码格式错误");
            }
        }

        jazSignupUserService.updateById(jazSignupUserDO);
        return Result.ok();
    }





    /**
     * 选手信息列表
     * @return
     */
    @GetMapping("/selSignupUserList")
    public Result<?> selSignupUserList(String name,String groupId){
        UserDO getUser = JWTUtil.getUser();
        EntityWrapper<JazSignupUserDO> entityWrapper =new EntityWrapper();
        if (name!=null&&!name.equals("")) {
            entityWrapper.eq("name", name);
        }
        if (groupId!=null&&!groupId.equals("")) {
            entityWrapper.eq("group_id", groupId);
        }
        entityWrapper.eq("user_id",getUser.getId()); //根据用户id查询
        entityWrapper.orderBy("update_time",false);
        List<JazSignupUserDO> list = jazSignupUserService.selectList(entityWrapper);
        for (int i=0;i<list.size();i++){
            JazSignupUserDO jazSignupUserDO = list.get(i);
            if (jazSignupUserDO.getType()==2){
                JazSignupGroupDO jazSignupGroupDO = jazSignupGroupService.selectById(jazSignupUserDO.getGroupId());
                jazSignupUserDO.setGroupName(jazSignupGroupDO.getName()); //组别名称

                JazSignupItemDO jazSignupItemDO = jazSignupItemService.selectById(jazSignupUserDO.getItemId());
                jazSignupUserDO.setItemName(jazSignupItemDO.getName()); //参赛项目名称
            }
        }
        return Result.ok(list);
    }


    /**
     * 队伍信息
     * @return
     */
    @GetMapping("/selTeamList")
    public Result<?> selTeamList(String groupId){
        UserDO getUser = JWTUtil.getUser();
        if (getUser==null){
            return Result.fail("请先进行登录后再选择队伍信息");
        }
        EntityWrapper<JazSignupTeamDO> entityWrapper =new EntityWrapper();
        if (groupId!=null&&!groupId.equals("")) {
            entityWrapper.eq("group_id", groupId);
        }
        entityWrapper.orderBy("update_time",false);
        List<JazSignupTeamDO> list = jazSignupTeamService.selectList(entityWrapper);
        return Result.ok(list);
    }




    /**
     * 是否展示报名入口
     * @return
     */
    @GetMapping("/isShow")
    public Result<?> selSignupUserList(){
        UserDO getUser = JWTUtil.getUser();
        EntityWrapper<JazSignupUserDO> entityWrapper =new EntityWrapper();
        entityWrapper.eq("user_id",getUser.getId()); //根据用户id查询
        List<JazSignupUserDO> list = jazSignupUserService.selectList(entityWrapper);
        return Result.ok(list.size()>0?1:0); //1展示，0不展示
    }






    /**
     * 选手信息回显
     * @return
     */
    @GetMapping("/selSignupUser")
    public Result<?> selSignupUser(Long id){
        JazSignupUserDO jazSignupUserDO = jazSignupUserService.selectById(id);
        // 选手类型
        if (jazSignupUserDO.getType()==2){
            JazSignupGroupDO jazSignupGroupDO = jazSignupGroupService.selectById(jazSignupUserDO.getGroupId());
            jazSignupUserDO.setGroupName(jazSignupGroupDO.getName()); //组别名称

            JazSignupItemDO jazSignupItemDO = jazSignupItemService.selectById(jazSignupUserDO.getItemId());
            jazSignupUserDO.setItemName(jazSignupItemDO.getName()); //参赛项目名称
        }

        return Result.ok(jazSignupUserDO);
    }



}
